<?php

namespace App\Console\Commands;

use App\Models\BlindBoxRecord;
use App\Services\BlindBoxService;
use Illuminate\Console\Command;

class BlindBoxAutoOpenCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'blindbox:auto-open';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '盲盒超过10分钟自动打开';
    /** @var BlindBoxService */
    private $blindBoxService;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(BlindBoxService $blindBoxService)
    {
        $tenMinutesAgo = now()->subMinutes(10);
        //查询10分钟前购买的未开启的盲盒记录， 每次最多开启100个
        $records = BlindBoxRecord::query()
            ->whereNull('user_asset_id')
            ->where('created_at', '<=', $tenMinutesAgo)
            ->limit(100)
            ->orderByDesc('id')
            ->get();

        foreach ($records as $record) {
            try {
                $blindBoxService->openBlindBox($record);
                $this->output->info(sprintf('盲盒开启成功[id=%s]', $record->id));
            } catch (\Exception $e) {
                $this->output->error(sprintf('盲盒开启失败[id=%s]:%s', $record->id, $e->getMessage()));

                continue;
            }
        }
    }
}
